<template>
    <el-upload
      class="upload-demo"
      :action="url"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-exceed="handleExceed"
      :on-preview="onPreview"
      :on-change="onChange"
      :on-progress="progress"
      :before-upload="beforeUpload"
      :before-remove="beforeRemove"
      :limit="2"
      :accept = "accept"
      :headers="myHeaders"
      :file-list="fileList"
      :show-file-list="uploadConfig.showFileList"
    >
      <slot name="content">
        <el-button size="mini" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip" v-if="uploadConfig.showTips && uploadConfig.showTipsBreak">需{{fileTypeTips}}格式,大小不能超过{{uploadConfig.maxSize}}MB</div>
        <span
          v-if="uploadConfig.showTips && !uploadConfig.showTipsBreak"
          slot="tip"
          class="el-upload__tip"
        >&nbsp;&nbsp;&nbsp;&nbsp;需{{fileTypeTips}}格式,大小不能超过{{uploadConfig.maxSize}}MB</span>
      </slot>
    </el-upload>
</template>

<!-- 只允许上传一个文件 -->
<script>
  import {getFileName} from '@/api/file'
  export default {
    name: "BaseInfo",
    model: {
      prop: 'fileCode',
      event: 'cc'
    },
    props:["config","fileCode"],
    watch:{
      fileCode(val){
        this.init();
      },
    },
    data() {
      return {
        myHeaders: {
          token: sessionStorage.getItem('token')
        },
        url: "/fileServer/file/upload",
        fileList: [],
        accept: "",
        imgAccept: ".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,",
        audioAccept: "audio/*",
        mp4Accpet: "video/mp4",
        zipAccpet: ".zip",
        fileTypeTips: "mp4",
        uploading: false,
        uploadConfig:{},
      }
    },
    mounted(){
      this.init();
    },
    methods: {
      init(){
        this.initConfig();
        if (this.uploadConfig.type == "mp4"){
          this.fileTypeTips = "mp4";
          this.accept = this.mp4Accpet;
        }else if(this.uploadConfig.type == "mp3"){
          this.fileTypeTips = "mp3";
          this.accept = this.audioAccept;
        } else if(this.uploadConfig.type == "img"){
          this.fileTypeTips = "图片";
          this.accept = this.imgAccept;
        } else if(this.uploadConfig.type == "zip"){
          this.fileTypeTips = "zip";
          this.accept = this.zipAccpet;
        }
        if (this.fileCode){
          this.initFileName({"code":this.fileCode});
        }else{
          this.fileList = [];
        }
      },
      initConfig(){
        let defaultConfigonfig = this.generateDefaultConfig();
        if (this.config) {
          Object.assign(defaultConfigonfig, this.config);
        }
        this.uploadConfig = defaultConfigonfig;
      },
      initFileName(params){
        //code可能为空
        if(params.code ==null || params.code == ''){
          return;
        }
        getFileName(params.code).then((res) => {
          if(res.code == 200){
            this.$set(this.fileList,0,{"name":res.data});
          }else{
            this.$message.error(res.message);
          }
        })
      },
      clear(){
        this.fileList = [];
        this.updateParentVal(null);
      },
      isUploading(msg){
        if (this.uploading) {
          this.$message.error(msg ? msg :"文件正在上传中，请等待上传完毕后再试!");
        }
        return this.uploading;
      },
      updateParentVal(val){
        this.$emit('cc', val)
      },
      generateDefaultConfig(){
        return {
          type: "mp4",//上传类型 ,mp3/mp4/img
          showFileList:true,//显示上传的文件名
          maxSize: 100, //文件大小，单位为M
          showTips: true, //是否显示提示信息
          showTipsBreak: true,//提示信息是否换行
        }
      },
      onPreview(){
        //点击文件列表中已上传的文件时的钩子
        this.$emit("onPreview");
      },
      handleRemove(file){
        //文件列表移除文件时的钩子
        if (file && file.status === 'success'){
          this.updateParentVal(null);
        }
        this.$emit("handleRemove",file);
      },
      handleSuccess(response, file, fileList){
        //文件上传成功时的钩子
        if (response.code == 200) {
          this.updateParentVal(response.data);
          // 设置允许文件替换上传
          this.fileList = fileList.slice(-1);
          this.$message.success(response.message);
        }else {
          this.$message.error(response.message)
          this.fileList = []
        }

        this.uploading = false;

        //自定义方法
        this.$emit("handleSuccess", response,file, fileList);
      },
      handleError(response, file, fileList){
        //文件上传失败时的钩子
        this.uploading = false;
        //自定义方法
        this.$emit("handleError", response,file, fileList);
      },
      handleExceed(files, fileList){
        //自定义方法
        this.$emit("handleExceed", files, fileList);
        //文件超出个数限制时的钩子
        // this.$message.warning("只能上传1个文件！");
      },
      progress(event, file, fileList){
        //自定义方法
        this.$emit("progress", event, file, fileList);
      },
      onChange(file, fileList){
        //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
        // this.fileList = fileList.slice(-1);
        //自定义方法
        this.$emit("onChange", file, fileList);
      },
      beforeUpload(file){
        const isLt2M = file.size  <= this.uploadConfig.maxSize * 1024 * 1024;
        const fileType = file.name.split(".")[file.name.split(".").length - 1];
         const isLt2M1 = file.size / 1024 > 0;
        if (!isLt2M) {
          this.$message.error("文件大小不能超过 "+this.uploadConfig.maxSize+"MB!");
          return false;
        }
        if (!isLt2M1) {
            this.$message.error('上传图片大小不能为0KB');
            return false;
          }
        if (this.uploadConfig.type == "mp4" && ["mp4","MP4"].indexOf(fileType)  == -1){
          this.$message.error("请上传mp4类型文件!");
          return false;
        } else if(this.uploadConfig.type == "img" && ["jpg", "png", "gif", "JPEG"].indexOf(fileType)  == -1){
          this.$message.error("请上传图片类型文件!");
          return false;
        } else if(this.uploadConfig.type == "mp3" && ["mp3","MP3"].indexOf(fileType)  == -1){
          this.$message.error("请上传mp3类型文件!");
          return false;
        }

        let parentFlag = true;
        this.$emit("beforeUpload", file,val => {parentFlag = val});
        if (!parentFlag) {
          return false;
        }

        this.uploading = true;
        return true;
      },
      beforeRemove(file, fileList){
        //删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
        //自定义方法
        this.$emit("beforeRemove", file,fileList)
      },
    }
  }
</script>

<style type="scss" scoped>
  .upload-demo{
    display: inline-block;
  }
</style>
